﻿using DevExpress.XtraEditors.Repository;
using Model.Dto;
using System.Collections.Generic;

namespace GridView
{
    public partial class CusCheckbox : DevExpress.XtraEditors.XtraForm
    {
        List<StudentDto> students = new List<StudentDto>() {
            new StudentDto() { Id = 1, Name = "小明", Chk = false },
            new StudentDto(){ Id = 2, Name = "小王", Chk=false }
        };
        public CusCheckbox()
        {
            InitializeComponent();
            gridControl1.DataSource = students;
        }

        RepositoryItemCheckEdit _disItemCheck;//声明用来替换‘选择’列复选框的对象
        RepositoryItemButtonEdit _disItemBtn;//声明用来替换‘申领’列按钮的对象
        private void gridView1_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        {
            //若当前进行到了“选择”列，
            if (e.Column.Name == "Chk")
            {

                //将单元格中的对象赋值给新声明的复选框对象
                _disItemCheck = (RepositoryItemCheckEdit)e.RepositoryItem.Clone();

                //设置只读属性
                _disItemCheck.Enabled = false;
                _disItemCheck.ReadOnly = true;
            }
            //if (e.Column.Name == "colAPPLY")
            //{
            //    _disItemBtn = (RepositoryItemButtonEdit)e.RepositoryItem.Clone();
            //    _disItemBtn.Buttons[0].Enabled = false;
            //}

            //如果当前行满足条件则替换
            if (students[e.RowHandle].Id == 1)
            {
                if (e.Column.Name == "Chk")
                {
                    e.RepositoryItem = _disItemCheck;
                }
                //else if (e.Column.Name == "colAPPLY")
                //{
                //    e.RepositoryItem = _disItemBtn;
                //}
            }
        }

        /// <summary>
        /// 使Cell单击修改Checkbox数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            var index = e.RowHandle;
            var obj = gridView1.GetRow(index);
            if (obj != null)
            {
                //如满足条件则不能对checkbox操作，扩展方法参考下面代码
                if (students[e.RowHandle].Id == 1)
                {
                }
                else
                {
                    var robj = obj as StudentDto;
                    robj.Chk = !robj.Chk;
                }
                this.gridView1.RefreshData();
            }
            return;
        }
    }
}